﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using CiStatus.CiStatusAddIn.Logic;
using CiStatus.CiStatusAddIn.Logic.PluginInterfaces;

namespace CiStatus.CiStatusAddIn.Views.ToolsOptionsViews
{
    public partial class NewProjectForm : Form
    {
        private bool _firstStep = true;
        private IEnumerator<KeyValuePair<string, ICiPollerParameter>> _wizardEnumerator;
        private AddSettingControl _currentControl;
        private string _lastKey;
        public IDictionary<string, string> Settings { get; set; }
        public KeyValuePair<string, string> Project { get; set; }
        public string PluginPath { get; set; }
     
        public NewProjectForm(string pluginPath)
        {
            PluginPath = pluginPath;
            InitializeComponent();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (_firstStep)
            {
                var selectedFactory = (ICiPollerFactory) cmbLoadedPollers.SelectedItem;
                Project = new KeyValuePair<string, string>(txtProject.Text.Trim(), selectedFactory.Name);
                Settings = new Dictionary<string, string>();
                var parameters = selectedFactory.CreateEmptyParameters();
                _wizardEnumerator = parameters.GetEnumerator();
                _lastKey = parameters.Keys.Last();
                ShowNextSetting();
                lblInfo.Text = "Fill in the Parameter below.";
            }
            else
            {
                Settings.Add(_currentControl.Pair);
                ShowNextSetting();
            }
            _firstStep = false;
        }

        private void ShowNextSetting()
        {
            if (_wizardEnumerator.MoveNext())
            {
                panelContent.Controls.Clear();
                _currentControl = new AddSettingControl(_wizardEnumerator.Current.Key);
                panelContent.Controls.Add(_currentControl);

                if (_wizardEnumerator.Current.Key.Equals(_lastKey))
                {
                    btnOk.Text = "Finish";
                }
            }
            else
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private void ProjectSettings_Load(object sender, EventArgs e)
        {
            var pluginFinder = new PluginFinder(PluginPath);
            var plugins = pluginFinder.Find();
            foreach (var plugin in plugins)
            {
                cmbLoadedPollers.Items.Add(plugin);
            }
            cmbLoadedPollers.SelectedIndex = 0;
            cmbLoadedPollers.DisplayMember = "Name";
        }
    }
}
